﻿using PlusAssistance.DAL.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlusAssistance.DAL.Concrete
{
    public class PagedList<T> : List<T>, IPagedList<T>
    {
        public PagedList()
        {

        }

        public PagedList(IQueryable<T> source, int pageIndex, int pageSize)
        {
            ProcessList(source);

            var total = source.Count();
            TotalCount = total;
            TotalPages = total / pageSize;
            if (total % pageSize > 0)
                TotalPages++;
            PageSize = pageSize;
            PageIndex = pageIndex;
            AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
            ResolveAvailablePages();
        }

        public PagedList(List<T> source, int pageIndex, int pageSize)
        {
            var total = source.Count();
            TotalCount = total;
            TotalPages = total / pageSize;
            if (total % pageSize > 0)
                TotalPages++;
            PageSize = pageSize;
            PageIndex = pageIndex;
            AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
            ResolveAvailablePages();
        }

        private void ResolveAvailablePages()
        {
            AvailablePages = new List<int>();
            var currentPage = PageIndex + 1;
            var lastPage = TotalPages;

            if (currentPage < 10)
            {
                for (var i = 1; i <= lastPage && i <= 10; i++)
                {
                    AvailablePages.Add(i);
                }
            }
            else if (currentPage >= 10)
            {
                for (var i = currentPage - 5; i <= lastPage && i < currentPage + 5; i++)
                {
                    AvailablePages.Add(i);
                }
            }

        }

        protected virtual void ProcessList(IQueryable<T> source)
        {

        }

        public List<int> AvailablePages { get; set; }

        public int PageIndex { get; private set; }

        public int PageSize { get; private set; }

        public int TotalCount { get; private set; }

        public int TotalPages { get; private set; }

        public bool HasPreviousPage
        {
            get { return (PageIndex > 0); }
        }

        public bool HasNextPage
        {
            get { return (PageIndex + 1 < TotalPages); }
        }
    }
}
